<?php

namespace app\admin\service;

use app\common\logic\CommonLogic;
use app\common\logic\DriverLogic;
use app\common\model\commonModel;
use app\common\model\trDriver;
use app\common\util\ErrorCode;
use think\facade\Env;

/**
 * Class Auth
 * @package app\admin\service
 * 提现服务类
 */
class TransferService
{
    private $params;
    private $returnData;
    private $mall_id = 0;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    //分页列表
    public function getList()
    {
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            if(is_numeric($this->params["search"])){
                $filter[] = ['transfer_sn', '=', $this->params["search"]];
            }else{
                $driverModel = new trDriver();
                $filter[] = ['driver_id', 'in', $driverModel->getColumn("id", [["nickname", "like", "{$this->params["search"]}%"], ["mall_id", "=", $this->mall_id]])];
            }
        }
        if(!empty($this->params['timeFrom']) && !empty($this->params['timeTo'])){
            $filter[] = ['create_time', '<=', strtotime($this->params['timeTo'])];
            $filter[] = ['create_time', '>=', strtotime($this->params['timeFrom'])];
        }
        if(isset($this->params['status'])){
            $filter[] = ['status', '=', $this->params['status']];
        }
        $data = commonModel::getList(transferTable, "*", $filter, $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $driverModel = new trDriver();//echo "<pre>";print_r($data);die("2");
            foreach ($data["data"] as $k => $item){
                if(empty($driverName[$item["driverId"]])){
                    $driverName[$item["driverId"]] = $driverModel->getValue("nickname", ["id" => $item["driverId"]]);
                }
                $data["data"][$k]["driverName"] = $driverName[$item["driverId"]];
                if(!empty($item["completeTime"]))
                    $data["data"][$k]["completeTime"] = date("Y-m-d H:i:s", $item["completeTime"]);
                if(!empty($item["createTime"]))
                    $data["data"][$k]["createTime"] = date("Y-m-d H:i:s", $item["createTime"]);
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 导出数据
    public function exportData(){
        $arr_header = ['ID', '提现人名称', '提现金额', '订单号', '交易单号', '申请时间', '处理状态'];
        $arr_width = ['8', '20', '10', '25', '25', '20', '10'];
        $arr_key = ['id', 'driverName', 'money', 'transferSn', 'tradeNo', 'createTime', 'status'];

        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            if(is_numeric($this->params["search"])){
                $filter[] = ['transfer_sn', '=', $this->params["search"]];
            }else{
                $driverModel = new trDriver();
                $filter[] = ['driver_id', 'in', $driverModel->getColumn("id", [["nickname", "like", "{$this->params["search"]}%"], ["mall_id", "=", $this->mall_id]])];
            }
        }
        if(!empty($this->params['timeFrom']) && !empty($this->params['timeTo']) && strtotime($this->params['timeTo'])){
            $filter[] = ['create_time', '<=', strtotime($this->params['timeTo'])];
            $filter[] = ['create_time', '>=', strtotime($this->params['timeFrom'])];
        }
        if(!empty($this->params['status'])){
            $filter[] = ['status', '=', $this->params['status']];
        }

        if(empty($filter)) {
            $data = commonModel::getList(transferTable, "*", $filter, $page, $pageSize, "create_time desc", false);
        }else{
            $data = commonModel::getFields(transferTable, "*", $filter, false, false);
        }
        if(!empty($data)) {
            $driverModel = new trDriver();
            foreach ($data as &$item) {
                if (empty($driverName[$item["driverId"]])) {
                    $driverName[$item["driverId"]] = $driverModel->getValue("nickname", ["id" => $item["driverId"]]);
                }
                $item["driverName"] = $driverName[$item["driverId"]];
                if (!empty($item["completeTime"]))
                    $item["completeTime"] = date("Y-m-d H:i:s", $item["completeTime"]);
                if (!empty($item["createTime"]))
                    $item["createTime"] = date("Y-m-d H:i:s", $item["createTime"]);
                $item["status"] = $item["status"] == "1" ? "申请中" : ($item["status"] == "2" ? "已提现" : "已拒绝");
            }
        }
        $res = CommonLogic::exportExcel(date("Y-m-d").'-提现申请数据导出', $arr_header, $arr_width, $arr_key, $data);
        if(is_array($res)) {
            $this->returnData["returnFile"] = $res;
            return $this->returnData;
        }
        return $this->returnData;
    }

    //信息
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = commonModel::getFields(transferTable, "*", ["id" => $this->params['id'], "mall_id" => $this->mall_id], true, false);
        if($data){
            if(!empty($data["completeTime"]))
                $data["completeTime"] = date("Y-m-d H:i:s", $data["completeTime"]);
            if(!empty($data["createTime"]))
                $data["createTime"] = date("Y-m-d H:i:s", $data["createTime"]);
            $driverModel = new trDriver();
            $data["driverName"] = $driverModel->getValue("nickname", ["id" => $data["driverId"]]);
        }
        $this->returnData['data'] = $data;
        return $this->returnData;
    }

    //更新状态
    public function toUpdateStatus(){ // status '状态：1未提现；2已提现；3已拒绝',
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        if(!isset($this->params['status'])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [2,3])){
            return ErrorCode::code("params_error", "status（2已提现；3已拒绝）");
        }
        $update["status"] = $this->params["status"];
        if($this->params["status"] == "2"){
            $data = commonModel::getFields(transferTable, "driver_id,money", ['id' => $this->params['id'], "status" => 1, "mall_id" => $this->mall_id]);
            if(!empty($data["money"])) {
                $driverModel = new trDriver();
                $openid = $driverModel->getValue("openid", ["id" => $data["driverId"]]);
                $res = DriverLogic::getHandleTransfer($openid, $data["money"]);
                if(isset($res["code"])){
                    $this->returnData = ErrorCode::code("fail");
                    $this->returnData["msg"] = $res["msg"];
                    return $this->returnData;
                }
                $update = array_merge($update, $res);
                $this->returnData["msg"] = "提现成功";
            }
        }
        $result = commonModel::toUpdate(transferTable, $update, ['id' => $this->params['id'], "mall_id" => $this->mall_id]);
        if(isset($result["code"])){
            return $result;
        }
        if($result) {
            return $this->returnData;
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新失败";
            return $this->returnData;
        }
    }

    //删除
    public function toDel(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = commonModel::getFields(transferTable, "status", ["id" => $this->params['id'], "mall_id" => $this->mall_id]);
        if(isset($data["status"]) && $data["status"] == "3") {
            $result = commonModel::delById(transferTable, $this->params['id']);
            if (!$result) {
                $this->returnData = ErrorCode::code("fail");
                $this->returnData["msg"] = "删除失败";
            }
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "不能删除";
        }
        return $this->returnData;
    }
}